import React, { useCallback, useEffect, useRef, useState } from 'react'
import request from '../utils/request'
import { useSelector } from 'react-redux'
import { RootState } from '../store'
import { UserState } from '../store/userReducer'
import { Dropdown, MenuProps, Tooltip } from 'antd'
import styles from '../style/app.module.less';
import {EditOutlined, SettingOutlined } from '@ant-design/icons';
import { useNavigate } from 'react-router-dom'

export interface Blog {
  id: number
  content: string
  remark: string
  cover: string
  tag: string
  title: string
  update_time: string
}

const BlogList: React.FC = () => {
  const user = useSelector<RootState, UserState>(state => state.user)
  const keyword = useSelector<RootState, string>(state => state.keyword)
  const [blogs, setBlogs] = useState<Blog[]>([])
  const blogsRef = useRef<Map<number, Blog>>(new Map())

  const navigate = useNavigate();
  useEffect(() => {
    async function fetchBlogs() {
      const result = await request('/api/blog', {
        params: { page: 1, pageSize: 10, keywords: keyword }
      })
      const list = result.data?.data?.list
      setBlogs(list || [])
    }
    let timer = setTimeout(() => {
      fetchBlogs()
    }, 500)
    return () => clearTimeout(timer)
  }, [keyword])
  const isLogin = user.userInfo.id > -1
  const handleClickBlog = useCallback((blogId: number) => {
    return () => {
      navigate(`/blog/${blogId}`)
    }
  }, [navigate])
  const getBlog = async (blogId: number) => {
    const blog = blogsRef.current.get(blogId)
    if (blog !== undefined) {
      return blog
    }
    const result = await request(`/api/blog/${blogId}`)
    const newBlog: Blog  = result.data.data[0]
    return newBlog
  }
  const handleEdit = useCallback((blogId: number) => {
    return async () => {
      const blog = await getBlog(blogId)
      navigate('/blog', {state: { blog }})
    }
  }, [navigate])
  const handleDelete = useCallback((blogId: number) => {
    return async () => {
      const blog = await request(`/api/blog/${blogId}`, {
        method: 'DELETE'
      })
      const blogsDel = blogs.filter(blog => blog.id !== blogId)
      setBlogs(blogsDel)
      console.log(blog, 'blog');
    }
  }, [blogs])
  const avatarItems: (blogId: number) => MenuProps["items"] = useCallback((blogId: number) => {
    return [
      {
        key: "1",
        icon: <EditOutlined />,
        label: (
          <div onClick={handleEdit(blogId)}>编辑</div>
        ),
      },
      {
        key: "2",
        icon: <SettingOutlined />,
        label: <div>设置</div>,
      },
      {
        key: "3",
        icon: <EditOutlined />,
        label: (
          <div onClick={handleDelete(blogId)}>删除</div>
        ),
      },
    ]
  }, [handleEdit, handleDelete])
  return (<div className={styles.bloglistContainer}>
    <div className={styles.bloglist}>
      {blogs.map(blog => {
        const {id, title, cover, tag, update_time } = blog
        return (
          <div key={id} className={styles.card}>
            <img
              onClick={handleClickBlog(id)}
              className={styles.cover}
              alt="cover"
              src={cover || '/api/load/dd67f280c5280d7d3c7f719c578ef1ff'}
            />
            <div className={styles.titleContainer}>
              {isLogin && <Dropdown menu={{ items: avatarItems(id) }} placement="bottomRight" arrow>
                <span className={styles.ellipsis}>···</span>
              </Dropdown>}
              <Tooltip 
                title={<span style={{color: '#000', fontSize: '10px'}}>{title}</span>} 
                placement="bottom" 
                color='#efefef'
                mouseEnterDelay={1.2}
              >
                <h3 className={styles.title} onClick={handleClickBlog(id)}>
                  {title}
                </h3>
              </Tooltip>
            </div>
            <div className={styles.subtitleContainer}>
              <span className={styles.up}>UP</span>
              <span className={styles.name}>{'阿锐仔'}</span>
              <span className={styles.dot}>·</span>
              <span className={styles.date}>{`${new Date(update_time).getMonth()+1}-${new Date(update_time).getDay()+1}`}</span>
              <span className={styles.tag}>{tag}</span>
            </div>
          </div>
        )
      })}
    </div>
  </div>)
}

export default BlogList
